/*
 * Copyright 2013-2020 Signal Messenger, LLC
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import com.quectel.aep.system.domain.vo.SysOSSPropertyPostSignatureVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class PostPolicyGenerator {

  public  static final DateTimeFormatter AWS_DATE_TIME   = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");
  private static final DateTimeFormatter CREDENTIAL_DATE = DateTimeFormatter.ofPattern("yyyyMMdd"          );

  private final String region;
  private final String bucket;
  private final String awsAccessId;

  public PostPolicyGenerator(String region, String bucket, String awsAccessId) {
    this.region      = region;
    this.bucket      = bucket;
    this.awsAccessId = awsAccessId;
  }

  public SysOSSPropertyPostSignatureVO getPolicy(ZonedDateTime now, String object, int maxSizeInBytes) {
    try {
      String expiration     = now.plusMinutes(30).format(DateTimeFormatter.ISO_INSTANT);
      String credentialDate = now.format(CREDENTIAL_DATE);
      String requestDate    = now.format(AWS_DATE_TIME  );
      String credential     = String.format("%s/%s/%s/s3/aws4_request", awsAccessId, credentialDate, region);

      String policy = String.format("{ \"expiration\": \"%s\",\n" +
              "  \"conditions\": [\n" +
              "    {\"bucket\": \"%s\"},\n" +
              "    {\"key\": \"%s\"},\n" +
              "    {\"acl\": \"public-read\"},\n" +
              "    [\"content-length-range\", 1, " + maxSizeInBytes + "],\n" +
              "    {\"x-amz-credential\": \"%s\"},\n" +
              "    {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\n" +
              "    {\"x-amz-date\": \"%s\" }\n" +
              "   ]\n" +
              "}", expiration, bucket, object, credential, requestDate);
      log.info("expiration:{}",expiration);
      log.info("bucket:{}",bucket);
      log.info("object:{}",object);
      log.info("credential:{}",credential);
      log.info("requestDate:{}",requestDate);
      SysOSSPropertyPostSignatureVO signatureVO=new SysOSSPropertyPostSignatureVO();
      signatureVO.setExpire(expiration);
      signatureVO.setAcl("public-read");
      signatureVO.setPolicy(Base64.encodeBase64String((policy.getBytes("UTF-8"))));
      signatureVO.setCredential(credential);
      signatureVO.setAlgorithm("AWS4-HMAC-SHA256");
      signatureVO.setKey(object);
      signatureVO.setPublicBucketName(bucket);
      signatureVO.setDate(requestDate);
      signatureVO.setAccessKeyId(awsAccessId);
      return signatureVO;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new AssertionError(e);
    }
  }
}